package com.spcmg.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spcmg.entity.SpcRoom;
import com.spcmg.entity.SpcStation;
import com.spcmg.enums.EnumSysCode;
import com.spcmg.mapper.SpcRoomMapper;
import com.spcmg.service.ISpcRoomService;
import com.spcmg.service.ISpcStationService;
import com.spcmg.utils.DateUtil;
import com.spcmg.utils.JsonResult;
import com.spcmg.utils.SequenceIdGenerator;
import com.spcmg.vo.SpcRoomVO;
import com.spcmg.vo.StatStationRoomNumVO;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 机房表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2021-04-13
 */
@Service
public class SpcRoomServiceImpl extends ServiceImpl<SpcRoomMapper, SpcRoom> implements ISpcRoomService {

    @Resource
    private SpcRoomMapper mapper;

    @Resource
    private ISpcStationService spcStationService;

    @Resource
    private SequenceIdGenerator sequenceIdGenerator;

    @Override
    public JsonResult insertRoom(String chinaName, String stationId, String address, String street, String x, String y,
                                 String area, String usedArea, Integer toHireBack, Integer hiredRack, String length,
                                 String width, String height, Integer classId, Integer typeId, Integer roomTypeDetail,
                                 String startUseDate, String maintenanceUnit, Integer flag, String notes) {
        // check机房名称是否唯一
        Integer num = mapper.countByChinaName(chinaName);
        if (num > 0) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_5002.getCode())
                    .message(EnumSysCode.ERR_5002.getMsg())
                    .build();
        }
        // check局站是否存在
        SpcStation stationEntity = spcStationService.getById(stationId);
        if (stationEntity == null) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_5009.getCode())
                    .message(EnumSysCode.ERR_5009.getMsg())
                    .build();
        }
        // IDC机房 TYPE_ID = 2050053，可出租机架数，已出租机架数必填
        if (typeId != null && typeId == 2050053) {
            if ( toHireBack == null || toHireBack == 0 || hiredRack == null || hiredRack == 0) {
                return JsonResult.failure()
                        .code(EnumSysCode.ERR_5008.getCode())
                        .message(EnumSysCode.ERR_5008.getMsg())
                        .build();
            }
        }
        // 保存
        SpcRoom entity = new SpcRoom();
        entity.setRoomId(sequenceIdGenerator.nextId());
        entity.setChinaName(chinaName);
        entity.setStationId(Long.valueOf(stationId));
        entity.setAddress(address);
        entity.setStreet(street);
        entity.setX(new BigDecimal(x).setScale(6, RoundingMode.HALF_DOWN));
        entity.setY(new BigDecimal(y).setScale(6, RoundingMode.HALF_DOWN));
        entity.setArea(new BigDecimal(area).setScale(2, RoundingMode.HALF_DOWN));
        entity.setUsedArea(new BigDecimal(usedArea).setScale(2, RoundingMode.HALF_DOWN));
        entity.setToHireRack(toHireBack);
        entity.setHiredRack(hiredRack);
        entity.setLength(new BigDecimal(length).setScale(2, RoundingMode.HALF_DOWN));
        entity.setWidth(new BigDecimal(width).setScale(2, RoundingMode.HALF_DOWN));
        entity.setHeight(new BigDecimal(height).setScale(2, RoundingMode.HALF_DOWN));
        entity.setClassId(classId);
        entity.setTypeId(typeId);
        entity.setRoomTypeDetail(roomTypeDetail);
        entity.setStartUseDate(DateUtil.parseLdt(startUseDate, "yyyy-MM-dd HH:mm:ss"));
        entity.setMaintenanceUnit(maintenanceUnit);
        entity.setFlag(flag);
        entity.setNotes(notes);
        this.save(entity);
        return JsonResult.success().build();
    }

    @Override
    @Transactional(rollbackFor = Throwable.class)
    public void saveBatchData(Collection<SpcRoom> roomList, Collection<SpcStation> stationList) {
        spcStationService.saveBatch(stationList);
        mapper.batchInsertOrUpdate(roomList);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int saveBatch(List<SpcRoom> spcRoomList) {
        long num = mapper.batchInsertOrUpdate(spcRoomList);
        return (int)num;
    }

    @Override
    public int selectCountByRoomChinaName(String chinaName) {
        return mapper.countByChinaName(chinaName);
    }

    @Override
    public List<StatStationRoomNumVO> statStationRoomNum(Long stationId) {
        List<Map<String, Object>> dataMapList = mapper.statStationRoomNum(stationId);
        List<StatStationRoomNumVO> resultList = new ArrayList<>();
        for (Map<String, Object> dataMap : dataMapList) {
            StatStationRoomNumVO view = new StatStationRoomNumVO();
            view.setStationId(MapUtils.getLong(dataMap, "STATION_ID"));
            view.setStationName(MapUtils.getString(dataMap, "CHINA_NAME"));
            view.setClassId(MapUtils.getInteger(dataMap, "CLASS_ID"));
            view.setTypeId(MapUtils.getInteger(dataMap, "TYPE_ID"));
            view.setClassName(MapUtils.getString(dataMap, "LEVE_NAME"));
            view.setTypeName(MapUtils.getString(dataMap, "TYPE_NAME"));
            view.setCount(MapUtils.getInteger(dataMap, "ROOM_COUNT"));
            resultList.add(view);
        }
        return resultList;
    }

    @Override
    public JsonResult selectSpcRoom(Integer type, String condition) throws Exception {
        List<Map<String, Object>> dataMapList = new ArrayList<>();
        switch (type) {
            case 1:
                dataMapList = mapper.selectSpcRoom(Long.valueOf(condition), null, null, null);
                break;
            case 2:
                dataMapList = mapper.selectSpcRoom(null, condition, null, null);
                break;
            case 3:
                dataMapList = mapper.selectSpcRoom(null, null, condition, null);
                break;
            case 4:
                dataMapList = mapper.selectSpcRoom(null, null, null, condition);
                break;
        }
        List<SpcRoomVO> viewList = new ArrayList<>();
        dataMapList.forEach(dataMap -> {
            SpcRoomVO view = new SpcRoomVO();
            view.setStationName(MapUtils.getString(dataMap, "STATION_NAME"));
            view.setRoomId(MapUtils.getLong(dataMap, "ROOM_ID"));
            view.setChinaName(MapUtils.getString(dataMap, "CHINA_NAME"));
            view.setStationId(MapUtils.getLong(dataMap, "STATION_ID"));
            view.setAddress(MapUtils.getString(dataMap, "ADDRESS"));
            view.setStreet(MapUtils.getString(dataMap, "STREET"));
            view.setX(new BigDecimal(MapUtils.getString(dataMap, "X")).setScale(6, RoundingMode.HALF_DOWN));
            view.setY(new BigDecimal(MapUtils.getString(dataMap, "Y")).setScale(6, RoundingMode.HALF_DOWN));
            view.setArea(new BigDecimal(MapUtils.getString(dataMap, "AREA", "0")).setScale(2, RoundingMode.HALF_DOWN));
            view.setUsedArea(new BigDecimal(MapUtils.getString(dataMap, "USED_AREA", "0")).setScale(2, RoundingMode.HALF_DOWN));
            view.setToHireRack(MapUtils.getInteger(dataMap, "TO_HIRE_RACK"));
            view.setHiredRack(MapUtils.getInteger(dataMap, "HIRED_RACK"));
            view.setLength(new BigDecimal(MapUtils.getString(dataMap, "LENGTH", "0")).setScale(2, RoundingMode.HALF_DOWN));
            view.setWidth(new BigDecimal(MapUtils.getString(dataMap, "WIDTH", "0")).setScale(2, RoundingMode.HALF_DOWN));
            view.setHeight(new BigDecimal(MapUtils.getString(dataMap, "HEIGHT", "0")).setScale(2, RoundingMode.HALF_DOWN));
            view.setClassId(MapUtils.getInteger(dataMap, "CLASS_ID"));
            view.setTypeId(MapUtils.getInteger(dataMap, "TYPE_ID"));
            view.setRoomTypeDetail(MapUtils.getInteger(dataMap, "ROOM_TYPE_DETAIL"));
            view.setStartUseDate(DateUtil.parseLdt(MapUtils.getString(dataMap, "SUD"), "yyyy-MM-dd HH:mm:ss"));
            view.setMaintenanceUnit(MapUtils.getString(dataMap, "MAINTENANCE_UNIT"));
            view.setFlag(MapUtils.getInteger(dataMap, "FLAG"));
            view.setNotes(MapUtils.getString(dataMap, "NOTES"));
            viewList.add(view);
        });
        return JsonResult.success()
                .data(viewList)
                .build();
    }
}
